package com.zhoug.android.common.utils;

import android.app.Activity;

/**
 * 在规定时间内连续按2次退出app
 *
 * @Author 35574
 * @Date 2022/4/20
 * @Description
 */
public class DoublePressExitApp {
    private static final String TAG = ">>>DoublePressExitApp";
    private static final boolean debug = false;

    /**
     * 限制生效时间:毫秒
     */
    private long mLimitTime = 2000;
    /**
     * 上传按键时间
     */
    private long lastTime;
    /**
     * 按键监听
     */
    private OnBackPressedListener mOnBackPressedListener;

    public DoublePressExitApp() {
        lastTime = 0;
    }

    /**
     * @param limitTime  限制生效时间:毫秒 默认2000
     */
    public DoublePressExitApp(long limitTime) {
        this();
        mLimitTime = limitTime;
    }


    public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener) {
        this.mOnBackPressedListener = onBackPressedListener;
    }

    /**
     * invoke in{@link Activity#onBackPressed()}
     */
    public void onBackPressed() {
        if (lastTime > 0 && System.currentTimeMillis() - lastTime <= mLimitTime) {
            if (debug) {
                LogUtils.d(TAG, "onBackPressed:第二次");
            }
            lastTime = 0;
            if (null != mOnBackPressedListener) {
                mOnBackPressedListener.onSecondPressed();
            }
        } else {
            lastTime = 0;
            lastTime = System.currentTimeMillis();
            if (debug) {
                LogUtils.d(TAG, "onBackPressed:第一次");
            }
            if (null != mOnBackPressedListener) {
                mOnBackPressedListener.onFirstPressed();
            }
        }
    }


    /**
     * 按键回掉
     */
    public interface OnBackPressedListener {
        void onFirstPressed();

        void onSecondPressed();
    }

}
